<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="false">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-collapse v-model="activeKey">
          <!-- 基本信息 -->
          <a-collapse-panel key="1" header="基本信息">
            <a-row :gutter="48">
              <a-col :span="12">
                <a-form-model-item label="物料编码" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="materialBill">
                  <a-input :disabled="formDisabled" v-model="model.materialBill" placeholder="请输入物料编码" disabled ></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item label="物料大类" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="provisionBroad">
                  <a-select
                    v-model="model.provisionBroad"
                    :disabled="formDisabled || upadateFlag"
                    placeholder="请选择物料大类"
                    :showSearch="true"
                    :allowClear="true"
                    :filterOption="filterOption"
                    @change="handleChange"
                    :getPopupContainer="triggerNode => {return triggerNode.parentNode}"
                  >
                    <a-select-option v-for="item in provisionBroadList" :key="item.id" :value="item.id">{{item.categoryName}}</a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item label="物料小类" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="provisionSmall">
                  <a-select
                    v-model="model.provisionSmall"
                    :disabled="formDisabled || upadateFlag"
                    placeholder="请选择物料小类"
                    :showSearch="true"
                    :allowClear="true"
                    :filterOption="filterOption"
                    :getPopupContainer="triggerNode => {return triggerNode.parentNode}"
                  >
                    <a-select-option v-for="item in provisionSmallList" :key="item.id" :value="item.id">{{item.categoryName}}</a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item label="物料名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="materialName">
                  <a-input :disabled="formDisabled" v-model="model.materialName" placeholder="请输入物料名称"  ></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item label="规格型号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="specification">
                  <a-input :disabled="formDisabled" v-model="model.specification" placeholder="请输入规格型号"  ></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item label="品牌" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="brand">
                  <a-input :disabled="formDisabled" v-model="model.brand" placeholder="请输入品牌"  ></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item label="制造商" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="manufacturer">
                  <a-input :disabled="formDisabled" v-model="model.manufacturer" placeholder="请输入制造商"  ></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item label="产地" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="production">
                  <a-input :disabled="formDisabled" v-model="model.production" placeholder="请输入产地"  ></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item label="参考价格（元）" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="referencePrice">
                  <a-input-number :disabled="formDisabled" :max="99999999" :min="0"  v-model="model.referencePrice" placeholder="请输入参考价格" style="width: 100%" />
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item label="单位" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="unit">
                  <j-dict-select-tag :disabled="formDisabled" type="list" v-model="model.unit" placeholder="请选择单位"  dictCode="unit_type" />
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="其他属性1" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="ohterOne">
                  <a-textarea :disabled="formDisabled" :max-length="500" v-model="model.ohterOne" rows="2" placeholder="请输入其他属性1"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="其他属性2" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="ohterTwo">
                  <a-textarea :disabled="formDisabled" :max-length="500" v-model="model.ohterTwo" rows="2" placeholder="请输入其他属性2"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="remark">
                  <a-textarea :disabled="formDisabled" :max-length="500" v-model="model.remark" rows="4" placeholder="请输入备注"/>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>
          <!-- 附件信息 -->
          <a-collapse-panel key="2" header="附件信息">
            <a-row :gutter="48">
              <a-col :span="24">
                <a-form-model-item prop="attachment">
                  <j-image-upload :disabled="formDisabled" isMultiple v-model="model.attachment"></j-image-upload>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>
        </a-collapse>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>

  import { httpAction, getAction } from '@/api/manage'

  export default {
    name: 'ErpMaterialForm',
    components: {
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    watch: {
      activeKey(key) {
        this.$forceUpdate()
      }
    },
    data () {
      return {
        activeKey: ['1','2'],
        model:{
          materialBill: null
        },
        labelCol: {
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 24 },
        },
        confirmLoading: false,
        validatorRules: {
        provisionBroad: [
            { required: true, message: '请选择供应大类!', trigger: 'blur'},
        ],
        provisionSmall: [
            { required: true, message: '请选择供应小类!', trigger: 'blur'},
        ],
        materialName: [
            { required: true, message: '请输入物料名称!', trigger: 'blur'},
        ],
        specification: [
            { required: true, message: '请输入规格型号!', trigger: 'blur'},
        ],
        //  上线前完善 2022年11月29日 8、物料管理中参考价格设置为非必填 2022年11月29日18:17:38 复原
        referencePrice: [
            { required: true, message: '请输入参考价格!', trigger: 'blur'},
            { pattern: /^(([1-9][0-9]*)|([0]\.\d{0,2}|[1-9][0-9]*\.\d{0,2}))$/, message: '请输入正确的参考价格!' },
        ],
        },
        url: {
          add: "/api/erp/purchase/material/erpMaterial/add",
          edit: "/api/erp/purchase/material/erpMaterial/edit",
          queryById: "/api/erp/purchase/material/erpMaterial/queryById",
          queryProvisionBroadList: "/api/erp/purchase/material/erpMaterialCategory/queryAllParent",
          queryProvisionSmallList: "/api/erp/purchase/material/erpMaterialCategory/queryChildrenByParentId",
          gainBillNo: '/api/erp/purchase/material/erpMaterial/gainBillNo'
        },
        provisionBroadList: [],
        provisionSmallList: [],
        upadateFlag: false
      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
    },
    created () {
       //备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
    },
    methods: {
      getBillNo () {
        const that = this
        getAction(this.url.gainBillNo).then((res) => {
          if (res.success) {
            that.model.materialBill = res.result// 单据编号
          }
        })
      },
      handleChange(value) {
        this.provisionSmallList = []
        this.$set(this.model, 'provisionSmall', undefined);
        this.$refs["form"].clearValidate('provisionSmall');
        if (!!value) {
          this.findProvisionSmallList(value)
        }
      },
      filterOption(input, option) {
        return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
        );
      },
      add () {
        this.edit(this.modelDefault);
      },
      edit (record) {
        this.$refs["form"].clearValidate();
        this.findProvisionBroadList()
        this.model = Object.assign({}, record);
        this.provisionSmallList = []
        if (!!this.model.provisionBroad) {
          this.findProvisionSmallList(this.model.provisionBroad)
          // 上线前完善 - 招采管理 1 物料管理编辑时物料大、小类可以修改
          // this.upadateFlag = true;
        } else {
          this.upadateFlag = false;
        }
        this.visible = true;
      },
      findProvisionBroadList() {
        const that = this
        that.provisionBroadList = []
        getAction(this.url.queryProvisionBroadList).then(res => {
          if (res.success) {
            res.result.forEach((res) => {
              that.provisionBroadList.push({ 'id':res.id, 'categoryName':res.categoryName })
            })
          } else {
            that.$message.warning(res.message)
          }
        })
      },
      findProvisionSmallList(value) {
        const that = this
        const parentId = value
        getAction(this.url.queryProvisionSmallList, { parentId }).then(res => {
          if (res.success) {
            res.result.forEach((res) => {
              that.provisionSmallList.push({ 'id':res.id, 'categoryName':res.categoryName })
            })
          } else {
            that.$message.warning(res.message)
          }
        })
      },
      submitForm () {
        const that = this;
        // 触发表单验证
        this.$refs.form.validate(valid => {
          if (valid) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if(!this.model.id){
              httpurl+=this.url.add;
              method = 'post';
            }else{
              httpurl+=this.url.edit;
               method = 'put';
            }
            httpAction(httpurl,this.model,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
              }else{
                that.$message.warning(res.message);
                that.$emit('unButtonDisable');
              }
            }).catch((error) => {
              that.$emit('unButtonDisable');
            }).finally(() => {
              that.confirmLoading = false;
            })
          } else {
            that.$emit('unButtonDisable');
          }
        })
      },
    }
  }
</script>
